package br.edu.ufcg.sig.query.persistencia.query;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import br.edu.ufcg.sig.query.ColumnInfo;
import br.edu.ufcg.sig.query.ConnectionUtils;
import br.edu.ufcg.sig.query.QueryTable;

public class QueryDAO {

	public QueryTable executeQuery(Connection connection, String query) throws SQLException {
		
		PreparedStatement prepareStatement = null;
		ResultSet result = null;
		try{
			prepareStatement = connection.prepareStatement(query);
			result = prepareStatement.executeQuery();
			
			ArrayList<ColumnInfo> columns = getColumnsLabels(result.getMetaData());
			
			ArrayList<String[]> values = getValues(result);
			
			QueryTable table = new QueryTable();
			table.setColumns(columns);
			table.setValues(values);
			
			return table;
		}finally{
			ConnectionUtils.closeResult(result);
			ConnectionUtils.closeStatement(prepareStatement);
		}		
	}

	private ArrayList<ColumnInfo> getColumnsLabels(ResultSetMetaData metaData) throws SQLException {
		ArrayList<ColumnInfo> columns = new ArrayList<ColumnInfo>();
		for(int i = 0; i < metaData.getColumnCount(); i++){
			columns.add(new ColumnInfo(metaData.getColumnLabel(i + 1), i));
		}
		return columns;
	}
	
	private ArrayList<String[]> getValues(ResultSet result) throws SQLException {
		ArrayList<String[]> values = new ArrayList<String[]>();
		int columnCount = result.getMetaData().getColumnCount();
		while(result.next()){
			String[] row = new String[columnCount];
			for(int i = 0; i < columnCount; i++){
				row[i] = result.getString(i + 1);
			}
			values.add(row);
		}
		return values;
	}

}
